package com.xky.ui.module.inventorManagement.update;

import com.xky.pojo.Inventory;
import com.xky.utils.DBUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class UpdateInvenTory extends JFrame {
    private JPanel mainPanel, headerPanel, formPanel, buttonPanel;
    private JTextField inventoryIdField, productIdField, warehouseIdField, quantityField, 
                       allocatedQuantityField, locationCodeField, batchNumberField,
                       expiryDateField, productNameField, warehouseNameField, supplierIdField;
    private JButton updateButton, queryButton;

    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    private static final Color QUERY_BUTTON_COLOR = new Color(46, 204, 113);
    
    // 日期格式化
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public UpdateInvenTory() {
        initializeFrame();
        initComponents();
        setVisible(true);
    }

    private void initializeFrame() {
        setTitle("库存信息修改");
        setSize(600, 700);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initComponents() {
        // 创建主面板并设置背景渐变
        mainPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                int w = getWidth();
                int h = getHeight();
                GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, w, h);
            }
        };
        mainPanel.setLayout(new BorderLayout(10, 10));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 1. 头部面板
        createHeaderPanel();

        // 2. 表单面板
        createFormPanel();

        // 3. 按钮面板
        createButtonPanel();

        // 添加事件监听
        setupEventListeners();

        add(mainPanel);
    }

    private void createHeaderPanel() {
        headerPanel = new JPanel(new BorderLayout());
        headerPanel.setOpaque(false);

        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setOpaque(false);

        JLabel titleLabel = new JLabel("库存信息修改");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        titleLabel.setForeground(PRIMARY_COLOR);
        titlePanel.add(titleLabel);

        JPanel hintPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        hintPanel.setOpaque(false);

        JLabel hintLabel = new JLabel("请输入库存ID查询后再修改");
        hintLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
        hintLabel.setForeground(Color.GRAY);
        hintPanel.add(hintLabel);

        // 添加分隔线
        JSeparator separator = new JSeparator();
        separator.setForeground(PRIMARY_COLOR);
        separator.setPreferredSize(new Dimension(450, 2));

        headerPanel.add(titlePanel, BorderLayout.NORTH);
        headerPanel.add(hintPanel, BorderLayout.CENTER);
        headerPanel.add(separator, BorderLayout.SOUTH);
        headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));

        mainPanel.add(headerPanel, BorderLayout.NORTH);
    }

    private void createFormPanel() {
        // 创建带圆角和阴影的面板
        JPanel formCard = createRoundedPanel();
        formCard.setLayout(new BorderLayout());

        formPanel = new JPanel(new GridBagLayout());
        formPanel.setOpaque(false);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);

        // 创建输入字段
        inventoryIdField = createStyledTextField(fieldFont);
        productIdField = createStyledTextField(fieldFont);
        warehouseIdField = createStyledTextField(fieldFont);
        quantityField = createStyledTextField(fieldFont);
        allocatedQuantityField = createStyledTextField(fieldFont);
        locationCodeField = createStyledTextField(fieldFont);
        batchNumberField = createStyledTextField(fieldFont);
        expiryDateField = createStyledTextField(fieldFont);
        productNameField = createStyledTextField(fieldFont);
        warehouseNameField = createStyledTextField(fieldFont);
        supplierIdField = createStyledTextField(fieldFont);

        // 添加字段到面板
        int row = 0;
        addFormField(row++, "库存ID *", inventoryIdField, labelFont, true);

        // 添加分组标签 - 库存信息
        JLabel inventoryGroupLabel = new JLabel("库存信息");
        inventoryGroupLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        inventoryGroupLabel.setForeground(PRIMARY_COLOR);
        gbc.gridx = 0;
        gbc.gridy = row++;
        gbc.gridwidth = 2;
        formPanel.add(inventoryGroupLabel, gbc);
        gbc.gridwidth = 1;
        
        addFormField(row++, "仓库ID *", warehouseIdField, labelFont, true);
        addFormField(row++, "当前库存数量 *", quantityField, labelFont, true);
        addFormField(row++, "已分配数量", allocatedQuantityField, labelFont, false);
        
        // 添加分组标签 - 批次信息
        JLabel batchGroupLabel = new JLabel("批次信息");
        batchGroupLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        batchGroupLabel.setForeground(PRIMARY_COLOR);
        gbc.gridx = 0;
        gbc.gridy = row++;
        gbc.gridwidth = 2;
        formPanel.add(batchGroupLabel, gbc);
        gbc.gridwidth = 1;
        
        addFormField(row++, "库位编码 *", locationCodeField, labelFont, true);
        addFormField(row++, "批次号 *", batchNumberField, labelFont, true);
        addFormField(row++, "过期日期 (yyyy-MM-dd) *", expiryDateField, labelFont, true);



        JScrollPane scrollPane = new JScrollPane(formPanel);
        scrollPane.setBorder(null);
        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
        
        formCard.add(scrollPane, BorderLayout.CENTER);
        formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        mainPanel.add(formCard, BorderLayout.CENTER);
    }

    private JTextField createStyledTextField(Font font) {
        JTextField field = new JTextField();
        field.setFont(font);
        field.setPreferredSize(new Dimension(250, 35));
        field.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 215, 230)),
                BorderFactory.createEmptyBorder(3, 5, 3, 5)
        ));
        return field;
    }

    private void addFormField(int row, String labelText, JComponent field, Font labelFont, boolean required) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(8, 8, 8, 8);
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.weightx = 0.3;
        gbc.anchor = GridBagConstraints.WEST;

        JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 0));
        labelPanel.setOpaque(false);
        
        JLabel label = new JLabel(labelText);
        label.setFont(labelFont);
        label.setForeground(PRIMARY_COLOR);
        labelPanel.add(label);

        formPanel.add(labelPanel, gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        formPanel.add(field, gbc);
    }

    private void createButtonPanel() {
        buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setOpaque(false);

        queryButton = new JButton("查询");
        styleButton(queryButton, QUERY_BUTTON_COLOR);

        updateButton = new JButton("修改");
        styleButton(updateButton, BUTTON_COLOR);

        // 初始状态下修改按钮不可用
        updateButton.setEnabled(false);

        buttonPanel.add(queryButton);
        buttonPanel.add(updateButton);

        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
    }

    private void styleButton(JButton button, Color bgColor) {
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setPreferredSize(new Dimension(120, 40));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
    }

    /**
     * 创建带圆角和阴影的面板
     */
    private JPanel createRoundedPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(Color.WHITE);
                g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
            }
        };
        panel.setOpaque(false);

        // 添加阴影边框
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createEmptyBorder(5, 5, 5, 5),
                BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
                        BorderFactory.createEmptyBorder(10, 10, 10, 10)
                )
        ));

        return panel;
    }

    private void setupEventListeners() {
        // 查询按钮事件
        queryButton.addActionListener(e -> {
            String inventoryIdStr = inventoryIdField.getText().trim();
            if (inventoryIdStr.isEmpty()) {
                JOptionPane.showMessageDialog(this, "请输入库存ID", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            try {
                int inventoryId = Integer.parseInt(inventoryIdStr);
                Inventory inventory = findInventoryById(inventoryId);
                if (inventory != null) {
                    // 填充表单数据
                    populateForm(inventory);
                    // 启用修改按钮
                    updateButton.setEnabled(true);
                } else {
                    JOptionPane.showMessageDialog(this, "未找到该库存记录", "提示", JOptionPane.WARNING_MESSAGE);
                    updateButton.setEnabled(false);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "输入错误", JOptionPane.WARNING_MESSAGE);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "查询失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        // 修改按钮事件
        updateButton.addActionListener(e -> {
            try {
                // 首先进行输入校验
                if (!validateInputs()) {
                    return; // 如果校验不通过，直接返回
                }

                Inventory inventory = getInventoryFromForm();
                
                if (updateInventory(inventory)) {
                    JOptionPane.showMessageDialog(this, "库存信息更新成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(this, "库存信息更新失败", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
    }

    private void populateForm(Inventory inventory) {
        inventoryIdField.setText(inventory.getInventoryId().toString());
        productIdField.setText(inventory.getProductId().toString());
        warehouseIdField.setText(inventory.getWarehouseId().toString());
        quantityField.setText(inventory.getQuantity().toString());
        
        if (inventory.getAllocatedQuantity() != null) {
            allocatedQuantityField.setText(inventory.getAllocatedQuantity().toString());
        } else {
            allocatedQuantityField.setText("");
        }
        
        locationCodeField.setText(inventory.getLocationCode());
        batchNumberField.setText(inventory.getBatchNumber());
        
        if (inventory.getExpiryDate() != null) {
            expiryDateField.setText(inventory.getExpiryDate().toLocalDate().format(DATE_FORMATTER));
        } else {
            expiryDateField.setText("");
        }

    }

    private Inventory getInventoryFromForm() {
        Inventory inventory = new Inventory();
        inventory.setInventoryId(Integer.valueOf(inventoryIdField.getText().trim()));
        inventory.setProductId(Integer.valueOf(productIdField.getText().trim()));
        inventory.setWarehouseId(Integer.valueOf(warehouseIdField.getText().trim()));
        inventory.setQuantity(Integer.valueOf(quantityField.getText().trim()));
        
        String allocatedQty = allocatedQuantityField.getText().trim();
        if (!allocatedQty.isEmpty()) {
            inventory.setAllocatedQuantity(Integer.valueOf(allocatedQty));
        }
        
        inventory.setLocationCode(locationCodeField.getText().trim());
        inventory.setBatchNumber(batchNumberField.getText().trim());
        
        String expiryDateStr = expiryDateField.getText().trim();
        if (!expiryDateStr.isEmpty()) {
            LocalDate expiryDate = LocalDate.parse(expiryDateStr, DATE_FORMATTER);
            inventory.setExpiryDate(LocalDateTime.of(expiryDate, LocalDateTime.now().toLocalTime()));
        }

        return inventory;
    }

    private boolean validateInputs() {
        // 1. 校验库存ID
        if (!validateRequiredField(inventoryIdField, "库存ID")) return false;

        // 2. 校验产品ID
        if (!validateRequiredField(productIdField, "产品ID")) return false;

        // 3. 校验仓库ID
        if (!validateRequiredField(warehouseIdField, "仓库ID")) return false;

        // 4. 校验库存数量
        if (!validateRequiredField(quantityField, "库存数量")) return false;

        // 5. 校验已分配数量（如果有值）
        if (!allocatedQuantityField.getText().trim().isEmpty() && 
            !validateNumericField(allocatedQuantityField, "已分配数量")) return false;

        // 6. 校验库位编码
        if (!validateRequiredField(locationCodeField, "库位编码")) return false;

        // 7. 校验批次号
        if (!validateRequiredField(batchNumberField, "批次号")) return false;

        // 8. 校验过期日期
        if (!validateRequiredField(expiryDateField, "过期日期")) return false;
        try {
            LocalDate.parse(expiryDateField.getText().trim(), DATE_FORMATTER);
        } catch (DateTimeParseException e) {
            showValidationError("过期日期格式不正确，请使用yyyy-MM-dd格式");
            return false;
        }


        // 所有校验通过
        return true;
    }

    private boolean validateRequiredField(JTextField field, String fieldName) {
        if (field.getText().trim().isEmpty()) {
            showValidationError(fieldName + "不能为空");
            field.requestFocus();
            return false;
        }
        return true;
    }

    private boolean validateNumericField(JTextField field, String fieldName) {
        try {
            Integer.parseInt(field.getText().trim());
            return true;
        } catch (NumberFormatException e) {
            showValidationError(fieldName + "必须是数字");
            field.requestFocus();
            return false;
        }
    }

    private void showValidationError(String message) {
        JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
    }

    private Inventory findInventoryById(int inventoryId) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("SELECT * FROM inventory WHERE inventory_id = ?");
            preparedStatement.setInt(1, inventoryId);
            resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                Inventory inventory = new Inventory();
                inventory.setInventoryId(resultSet.getInt("inventory_id"));
                inventory.setProductId(resultSet.getInt("product_id"));
                inventory.setWarehouseId(resultSet.getInt("warehouse_id"));
                inventory.setQuantity(resultSet.getInt("quantity"));
                
                inventory.setAllocatedQuantity(resultSet.getInt("allocated_quantity"));
                if (resultSet.wasNull()) {
                    inventory.setAllocatedQuantity(null);
                }
                
                inventory.setLocationCode(resultSet.getString("location_code"));
                inventory.setBatchNumber(resultSet.getString("batch_number"));
                
                Timestamp expiryDate = resultSet.getTimestamp("expiry_date");
                if (expiryDate != null) {
                    inventory.setExpiryDate(expiryDate.toLocalDateTime());
                }
                
                Timestamp lastStockUpdate = resultSet.getTimestamp("last_stock_update");
                if (lastStockUpdate != null) {
                    inventory.setLastStockUpdate(lastStockUpdate.toLocalDateTime());
                }
                
                Timestamp createdTime = resultSet.getTimestamp("created_time");
                if (createdTime != null) {
                    inventory.setCreatedTime(createdTime.toLocalDateTime());
                }
                
                Timestamp updatedTime = resultSet.getTimestamp("updated_time");
                if (updatedTime != null) {
                    inventory.setUpdatedTime(updatedTime.toLocalDateTime());
                }

                return inventory;
            }
            return null;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, resultSet);
        }
    }

    private boolean updateInventory(Inventory inventory) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement(
                    "UPDATE inventory SET product_id = ?, warehouse_id = ?, quantity = ?, " +
                    "allocated_quantity = ?, location_code = ?, batch_number = ?, " +
                    "expiry_date = ?, last_stock_update = NOW(), updated_time = NOW() WHERE inventory_id = ?");
            
            preparedStatement.setInt(1, inventory.getProductId());
            preparedStatement.setInt(2, inventory.getWarehouseId());
            preparedStatement.setInt(3, inventory.getQuantity());
            
            if (inventory.getAllocatedQuantity() != null) {
                preparedStatement.setInt(4, inventory.getAllocatedQuantity());
            } else {
                preparedStatement.setNull(4, Types.INTEGER);
            }
            
            preparedStatement.setString(5, inventory.getLocationCode());
            preparedStatement.setString(6, inventory.getBatchNumber());
            
            if (inventory.getExpiryDate() != null) {
                preparedStatement.setTimestamp(7, Timestamp.valueOf(inventory.getExpiryDate()));
            } else {
                preparedStatement.setNull(7, Types.TIMESTAMP);
            }
            preparedStatement.setInt(8,inventory.getInventoryId());
            return preparedStatement.executeUpdate() > 0;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(UpdateInvenTory::new);
    }
}

